import { ObjectDirective } from "vue";

const longPress: ObjectDirective = {
  mounted(el: any, binding: any, vNode: any) {
    // 确保提供的表达式是函数
    const { handler: handleFun, params } = binding.value
    let action = ''
    if (typeof handleFun !== 'function') {
      // 获取组件名称
      const compName = vNode.context.name;
      let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be`;
      if (compName) { warn += `Found in component '${compName}'`; }

      console.warn(warn);
    }

    // 定义变量
    let pressTimer: any = null;
    let startTime: number
    let endTime: number
    // 创建计时器（ 1秒后执行函数 ）
    let start = (e: any) => {
      e.preventDefault();
      startTime = new Date().getTime();
      if (e.type === 'click' && e.button !== 0) {
        return;
      }

      if (pressTimer === null) {
        pressTimer = setTimeout(() => {
          // 执行函数
          action = 'longPress'
          handler(e);
        }, 500);
      }
    }

    // 取消计时器
    let cancel = (e: any) => {
      action = 'click'
      handler(e);
      if (pressTimer !== null) {
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    }

    // 取消计时器 判断点击还是长按
    let end = (e: any) => {
      endTime = new Date().getTime();
      action = (endTime - startTime) > 500 ? 'longPress' : 'click'
      if (action === 'click') handler(e);
      if (pressTimer !== null) {
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    }

    // 运行函数
    const handler = (e: any) => {
      let location
      if (action === 'longPress') {
        location = {
          clientX: e.targetTouches[0].clientX,
          clientY: e.targetTouches[0].clientY,
        }
      }
      binding.value.handler(location, action, params);
    }

    // 添加事件监听器
    el.addEventListener('mousedown', start);
    el.addEventListener('touchstart', start);
    el.addEventListener('click', cancel);
    el.addEventListener('mouseout', end);
    el.addEventListener('touchend', end);
    el.addEventListener('touchcancel', end);
  }
};

export default longPress;